import Vue from 'vue'
import Router from 'vue-router'
// 主页模板路由
const Home = () => import(/* webpackChunkName: "home_index_product_detail" */ '../pages/home.vue')
// 首页路由
const Index = () => import(/* webpackChunkName: "home_index_product_detail" */ '../pages/index.vue')
// 产品展示路由
const Product = () => import(/* webpackChunkName: "home_index_product_detail" */ '../pages/product.vue')
// 产品详情路由
const Detail = () => import(/* webpackChunkName: "home_index_product_detail" */ '../pages/detail.vue')

// 订单模板路由
const Order = () => import(/* webpackChunkName: "order_list_confirm" */ '../pages/order.vue')
// 订单列表路由
const OrderList = () => import(/* webpackChunkName: "order_list_confirm" */ '../pages/orderList.vue')
// 订单确认路由
const OrderConfirm = () => import(/* webpackChunkName: "order_list_confirm" */ '../pages/orderConfirm.vue')

Vue.use(Router)

const router = new Router({
  routes: [{
    path: '/',
    name: 'home',
    component: Home,
    redirect: '/index',
    children: [{
      path: '/index',
      name: 'index',
      component: Index
    }, {
      path: '/product/:id',
      name: 'product',
      component: Product
    }, {
      path: '/detail/:id',
      name: 'detail',
      component: Detail
    }]
  }, {
    path: '/cart',
    name: 'cart',
    component: () => import('../pages/cart.vue')
  }, {
    path: '/order',
    name: 'order',
    component: Order,
    children: [{
      path: 'list',
      name: 'order-list',
      component: OrderList
    }, {
      path: 'confirm',
      name: 'order-confirm',
      component: OrderConfirm
    }, {
      path: 'pay',
      name: 'order_pay',
      component: () => import('../pages/orderPay.vue')
    }, {
      path: 'alipay',
      name: 'alipay',
      component: () => import('../pages/alipay.vue')
    }]
  }, {
    path: '/login',
    name: 'login',
    component: () => import('../pages/login.vue')
  }, {
    path: '/register',
    name: 'register',
    component: () => import('../pages/register.vue')
  }]
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from代表从哪个路径跳转而来
  // next是一个函数，表示放行  next() 放行  next('/goodList')强制跳转
  // 如果用户访问的是index直接放行
  if (to.path === '/index' || to.path === '/login' || to.path === '/register') return next()
  // 如果用户访问购物车和订单页面判断sessionStorage中是否有id
  if (to.path === '/cart' || to.path === '/order') {
    const userId = Vue.$cookies.get('userId') || ''
    console.log(userId)
    if (!userId) return next('/index') // 强制跳转商品页面
  }
  // 有id
  next()
})

export default router
